import React, { useState, useEffect } from 'react';
import {Text, View} from "react-native";

const CountdownTimer = ({ createTime, countdownMinutes, color = 'red' }) => {
    const [timeLeft, setTimeLeft] = useState(countdownMinutes * 60); // 将倒计时转换为秒数

    useEffect(() => {
        // 计算剩余时间的函数
        const calculateTimeLeft = () => {
            const now = new Date();
            const createdTime = new Date(createTime);
            const timeElapsed = Math.floor((now - createdTime) / 1000);
            const remainingTime = countdownMinutes * 60 - timeElapsed;
            setTimeLeft(Math.max(remainingTime, 0)); // 确保剩余时间不为负数
        };

        // 初始计算
        calculateTimeLeft();

        // 每秒更新一次倒计时
        const timer = setInterval(calculateTimeLeft, 1000);

        // 清除计时器
        return () => clearInterval(timer);
    }, [createTime, countdownMinutes]);

    // 计算分钟和秒数
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;

    return (
        <Text style={{ color: color }}>{minutes < 10 ? `0${minutes}` : minutes}:{seconds < 10 ? `0${seconds}` : seconds}</Text>
    );
};

export default CountdownTimer;
